const { BackendRequestError, BackendUploadError } = require('./errors/backenderror');
const cacheStorage = require('./localstorage');

function selectBackendUrl() {
    const systemInfo = uni.getSystemInfoSync();
    const version = __wxConfig.envVersion;
    const platform = systemInfo.platform;
    console.log(version, platform);
    if (version === 'develop' && platform === 'devtools') {
        return 'http://127.0.0.1:3000';
    }
    switch (version) {
        case 'trial':
            return '';
        case 'release':
            return '';
        case 'develop':
            return '';
        default:
            return '';
    }
}

const backendUrl = selectBackendUrl();
let globalToken = null;

console.log('backendUrl', backendUrl);

async function setToken(token) {
    globalToken = token;
    uni.setBackgroundFetchToken({
        token: token
    });
}

async function getToken() {
    return globalToken;
}

/**
 * @Description 发送请求
 * @author 53010
 * @date 2020/6/29 17:51
 * @param {String} config.path 请求路径
 * @param {String} [config.host] 请求域名
 * @param {String} [config.method] 请求方式 POST|GET
 * @param {String} [config.header] 请求头字典
 * @param {String} [config.isAuth] 是否需要Token
 * @param {Object} [config.data] 请求参数
 * @param {Object} [config.disableCheck] 关闭状态检查
 * @param {Number} [config.timeout] 超时时间
 */
async function sendRequest(config) {
    uni.showLoading({
        title: '加载中',
        mask: true
    });
    if (!config.path) {
        throw new Error('no path');
    }
    config.method = config.method || 'GET';
    config.header = config.header || {};
    config.timeout = config.timeout || 15 * 1000;
    config.isAuth = config.isAuth === undefined ? true : config.isAuth;
    if (config.isAuth) {
        const token = await getToken();
        config.header.authorization = token || await requireToken();
    }
    const requestHost = config.host || backendUrl;
    const [err, res] = await uni.request({
        url: requestHost + config.path,
        header: config.header,
        data: config.data,
        dataType: 'json',
        method: config.method,
        timeout: config.timeout,
        enableHttp2: true,
        enableCache: true
    });
    if (err) {
        uni.hideLoading();
        console.error(JSON.stringify(err));
        throw new BackendRequestError(err);
    }
    if (config.disableCheck) {
        return res.data;
    }
    if (res.data.status !== 'success') {
        uni.hideLoading();
        if (res.data.errcode === 'RouterTokenError') await requireToken();
        console.error({ code: res.data.errcode, msg: res.data.errmsg });
        throw new BackendRequestError({ code: res.data.errcode, msg: res.data.errmsg });
    }
    uni.hideLoading();
    return res.data;
}

/**
 * @Description 上传请求
 * @author 53010
 * @date 2020/6/29 17:51
 * @param {String} config.path 请求路径
 * @param {String} config.filepath 要上传文件的路径
 * @param {String} [config.host] 请求域名
 * @param {String} [config.header] 请求头字典
 * @param {String} [config.isAuth] 是否需要Token
 * @param {Object} [config.data] 请求参数
 * @param {Object} [config.disableCheck] 关闭状态检查
 * @param {Number} [config.timeout] 超时时间
 */
async function uploadRequest(config) {
    uni.showLoading({
        title: '加载中',
        mask: true
    });
    if (!config.path || !config.filepath) {
        throw new Error('no path or no file path');
    }
    config.header = config.header || {};
    config.timeout = config.timeout || 60 * 1000;
    config.isAuth = config.isAuth === undefined ? true : config.isAuth;
    if (config.isAuth) {
        config.header.authorization = await getToken();
    }
    const requestHost = config.host || backendUrl;

    const [err, res] = await uni.uploadFile({
        url: requestHost + config.path,
        filePath: config.filepath,
        name: 'file',
        header: config.header,
        dataType: 'json',
        timeout: config.timeout
    });

    if (err) {
        console.error(err);
        throw new BackendUploadError(err);
    }
    if (config.disableCheck) {
        return res.data;
    }
    const result = JSON.parse(res.data);
    if (result.status !== 'success') {
        console.log({ code: result.errcode, msg: result.errmsg });
        throw new BackendUploadError({ code: result.errcode, msg: result.errmsg });
    }
    uni.hideLoading();
    return result;
}

/**
 * 请求token
 * @returns {Promise<*>}
 */
async function requireToken() {
    uni.showLoading({
        title: '加载中',
        mask: true
    });
    const [loginError, loginResult] = await uni.login({ provider: 'weixin' });
    if (loginError) {
        console.error(loginError);
        return;
    }
    const [tokenError, tokenResult] = await uni.request({
        url: backendUrl + '/mp/user/wxlogin',
        data: { code: loginResult.code },
        method: 'POST',
        dataType: 'json',
        timeout: 15 * 1000,
        enableHttp2: true,
        enableCache: true
    });
    if (tokenError) {
        console.error(tokenError);
        return;
    }
    const token = tokenResult.data.data;
    console.log(token);
    await setToken(token);
    await cacheStorage.writeCache('token', token, 43200);
    uni.hideLoading();
    return token;
}

module.exports = {
    sendRequest,
    uploadRequest
};
